package com.hotlove.usercenter.service.impl;

import com.hotlove.tools.cache.CacheConstant;
import com.hotlove.tools.cache.CacheUtil;
import com.hotlove.tools.common.Constant;
import com.hotlove.tools.common.MD5Util;
import com.hotlove.tools.exception.CommonException;
import com.hotlove.usercenter.dao.ProfileMapper;
import com.hotlove.usercenter.domain.Profile;
import com.hotlove.usercenter.domain.ProfileExample;
import com.hotlove.usercenter.dto.Crendential;
import com.hotlove.usercenter.service.CredentialService;
import com.hotlove.usercenter.service.ProfileService;
import com.hotlove.usercenter.vo.ProfileVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: hotlove_linx
 * @Date: 2022/4/5 16:23
 * @Description:
 */
@Service
public class ProfileServiceImpl implements ProfileService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ProfileMapper profileMapper;

    @Resource
    private CredentialService credentialService;

    @Override
    public Long registerProfile(Profile profile) throws CommonException {
        Long id = CacheUtil.getInstance().incrAndGet(CacheConstant.PROFILE_ID_KEY+"-profile-id");
        profile.setId(id);
        profile.setDeleted(Constant.UNDELETED);
        // 将密码进行md5加密
        profile.setPassword(MD5Util.encrypt(profile.getPassword()));

        try {
            profileMapper.insertSelective(profile);
        } catch (Exception e) {
            logger.info(e.toString());
            throw new CommonException("注册用户信息失败");
        }

        return id;
    }

    @Override
    public Crendential login(Integer terminal, String userName, String password) throws CommonException {
        ProfileExample profileExample = new ProfileExample();
        profileExample.createCriteria().andNameEqualTo(userName)
                .andPasswordEqualTo(MD5Util.encrypt(password))
                .andDeletedEqualTo(Constant.UNDELETED);

        List<Profile> profiles = profileMapper.selectByExample(profileExample);
        if (CollectionUtils.isEmpty(profiles)) {
            throw new CommonException("登录失败，用户名或密码错误");
        }

        Profile profile = profiles.get(0);

        // 登录成功 缓存登录信息到redis并生成token
        return credentialService.createCredential(terminal, profile);
    }

    @Override
    public Profile queryProfileById(Long profileId) {

        ProfileExample profileExample = new ProfileExample();
        profileExample.createCriteria().andIdEqualTo(profileId);

        return profileMapper.selectByPrimaryKey(profileId);
    }
}
